from rest_framework.response import Response
from rest_framework.views import APIView
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
import json
from db import Dd

db1 = Dd()


# Create your views here.
def showuseraudit(request):
    sql = "select c.id,c.name,c.tmoney,c.company_name,c.status from customer as c left join reg_form as rf on c.reformid=rf.id left join customer_manager as cm on cm.id=c.managerid"
    print("324234234")
    res = db1.get_all(sql)
    return JsonResponse({"code": 200, 'list': res})


import json


def audit(request):
    import time
    # 获取参数
    data = json.loads(request.body)
    time = int(time.time())
    ssql = "select * from customer where id=%d" % (int(data['id']))
    customer = db1.get_one(ssql)

    # 更新constmer表，状态，审核人，审核时间
    sql = "update customer set status=%d,audit_time=%d,audit_name='zs' where id=%d" % (
        int(data['is_agree']), time, int(data['id']))
    db1.update(sql)

    # 更新来源表
    sql1 = "select id,tcount from reg_form where id=%d" % (int(customer['reformid']))
    regform = db1.get_one(sql1)
    number = int(regform['tcount']) + 1
    sql2 = 'update reg_form set tcount=%d where id=%d' % (int(number), int(customer['reformid']))
    db1.update(sql2)
    # 更新客户经理中的总金额
    sql3 = "select * from customer_manager where id=%d" % (int(customer['managerid']))
    manager = db1.get_one(sql3)
    number = int(manager['tmoney']) + int(customer['tmoney'])

    sql4 = 'update customer_manager set tmoney=%d where id=%d' % (int(number), int(customer['managerid']))
    db1.update(sql4)
    return JsonResponse({"code": 200})


def getmes(request):
    sql = 'select name,tcount from reg_form'
    res = db1.get_all(sql)
    print(res)
    list = [{'value': i['tcount'], 'name': i['name']} for i in res]
    return JsonResponse({"code": 200, 'list': list})


def getcustomer(request):
    sql = 'select * from customer'
    res = db1.get_all(sql)
    return JsonResponse({"code": 200, 'list': res})


from dwebsocket.decorators import accept_websocket

websocketlist = []


@accept_websocket
def websocket_conn(request):
    if request.is_websocket:
        websocketlist.append(request.websocket)

    for message in request.websocket:
        break

    # 发送消息


def sendmes(request):
    data = request.POST
    if websocketlist:
        for i in websocketlist:
            mes = [{'name': data['name']}]
            b1 = json.dumps(mes, ensure_ascii=False).encode('utf-8')
            i.send(b1)
    return HttpResponse('ok')
